package com.eclipse.training.listeners;

import java.util.ArrayList;

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;

import com.eclipse.training.model.Asteroid;
import com.eclipse.training.model.DarkMatter;
import com.eclipse.training.model.Galaxy;
import com.eclipse.training.model.GalaxyCluster;
import com.eclipse.training.model.Nebula;
import com.eclipse.training.model.Planet;
import com.eclipse.training.model.Satellite;
import com.eclipse.training.model.SolarSystem;
import com.eclipse.training.model.Star;
import com.eclipse.training.model.StarCluster;

public class TreeSelectionChangeListener implements ISelectionChangedListener {

	private TableViewer tableViewer;

	public TreeSelectionChangeListener(TableViewer tableViewer) {
		this.tableViewer = tableViewer;
	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		IStructuredSelection selection = (IStructuredSelection) event
				.getSelection();

		Object element = selection.getFirstElement();
		ArrayList<Object> input = new ArrayList<Object>();

		/*
		 * Retrieve the elements to show in the target viewer
		 */
		if (element instanceof Asteroid) {
			input.add(element);
		} else if (element instanceof DarkMatter) {
			input.add(element);
		} else if (element instanceof Galaxy) {
			input.addAll(((Galaxy) element).getStars());
			input.addAll(((Galaxy) element).getNebulae());
			input.addAll(((Galaxy) element).getStarClusters());
		} else if (element instanceof GalaxyCluster) {
			input.addAll(((GalaxyCluster) element).getGalaxies());
		} else if (element instanceof Nebula) {
			input.add(element);
		} else if (element instanceof Planet) {
			input.addAll(((Planet) element).getSatellites());
		} else if (element instanceof Satellite) {
			input.add(element);
		} else if (element instanceof SolarSystem) {
			input.addAll(((SolarSystem) element).getAsteroids());
			input.addAll(((SolarSystem) element).getPlanets());
			input.addAll(((SolarSystem) element).getStars());
		} else if (element instanceof Star) {
			SolarSystem star;
			if ((star = ((Star) element).getSystems()) != null)
				input.add(star);
		} else if (element instanceof StarCluster) {
			input.addAll(((StarCluster) element).getStars());
		}

		if (input.size() == 0 && element != null)
			input.add(element);

		/*
		 * Update the target viewer
		 */
		tableViewer.setInput(input);
		tableViewer.refresh();
	}
}
